package com.kgc.sbt.provider111;

import com.alibaba.dubbo.config.annotation.Service;
import com.kgc.sbt.api.OrderApi;
import com.kgc.sbt.beans.*;
import com.kgc.sbt.constant.SystemConstant;
import com.kgc.sbt.mapper.*;
import com.kgc.sbt.beans.ArrivalReminderExample;
import com.kgc.sbt.utils.PageSupport;
import com.kgc.sbt.utils.ResultBuildUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * Created on 2022/11/17.
 * <p>
 * Author: wuqilong
 * <p>
 * Description: 订单服务提供者
 */
@Service
@Slf4j
public class orderProider implements OrderApi {

    @Autowired
    private OrderMainMapper orderMainMapper;

    @Autowired
    private LogisticsInfoMapper logisticsInfoMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private ArrivalReminderMapper arrivalReminderMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private UserCouponsMapper userCouponsMapper;

    @Autowired
    private VipMapper vipMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private UserInformationMapper userInformationMapper;

    @Autowired
    private UserLoginMapper userLoginMapper;

    @Override
    public Integer selectUserIdByToken(String token) {
        UserLoginExample userLoginExample = new UserLoginExample();
        userLoginExample.createCriteria().andTokenEqualTo(token);
        if(userLoginMapper.selectByExample(userLoginExample) == null || userLoginMapper.selectByExample(userLoginExample).size() == 0){
            // 依据token查询列表为空，代表token有误
            return 0;
        }

        // token正确，返回其对应的用户id
        return userLoginMapper.selectByExample(userLoginExample).get(0).getUserId();
    }

    @Override
    public List<Cart> getCartInfo(Integer userId) {

        CartExample cartExample = new CartExample();

        // checked为1代表商品被选中
        cartExample.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(1);

        return cartMapper.selectByExample(cartExample);
    }

    @Override
    public Address getAddressInfo(Integer userId) {

        AddressExample addressExample = new AddressExample();

        addressExample.createCriteria().andUserIdEqualTo(userId);

        return addressMapper.selectByExample(addressExample).get(0);
    }

    @Override
    public List<UserCoupons> getCouponsInfo(Integer userId) {

        UserCouponsExample userCouponsExample = new UserCouponsExample();

        userCouponsExample.createCriteria().andUserIdEqualTo(userId).andEndTimeGreaterThan(new Date());

        return userCouponsMapper.selectByExample(userCouponsExample);
    }

    @Override
    public int getVipInfo(Integer userId) {
        return vipMapper.selectVipStatusByUserId(userId);
    }

    @Override
    public boolean putOrderMain(OrderMain orderMain) {
        return orderMainMapper.insert(orderMain) > 0;
    }

    @Override
    public Product getProductById(Integer productId) {
        return productMapper.selectByPrimaryKey(productId);
    }

    @Override
    public boolean putOrderDetail(OrderDetail orderDetail) {
        return orderDetailMapper.insert(orderDetail) > 0;
    }

    @Override
    public boolean updUserPoints(Integer userId, Integer integral) {
        UserLoginExample userLoginExample = new UserLoginExample();
        userLoginExample.createCriteria().andUserIdEqualTo(userId);
        UserLogin userLogin = userLoginMapper.selectByExample(userLoginExample).get(0);
        userLogin.setIntegral(userLogin.getIntegral() + integral);
        return userLoginMapper.updateByPrimaryKey(userLogin) > 0;
    }

    @Override
    public boolean updProductStock(Integer productId, Integer quantity) {
        StockExample stockExample = new StockExample();
        stockExample.createCriteria().andProductIdEqualTo(productId);
        Stock stock = stockMapper.selectByExample(stockExample).get(0);
        stock.setCount(stock.getCount() - quantity);
        return stockMapper.updateByPrimaryKey(stock) > 0;
    }

    @Override
    public PageSupport<OrderMain<OrderDetail>> getOrderByStatus(Integer userId, Integer orderStatus, Integer currPageNo, Integer pageSize) {

        PageSupport<OrderMain<OrderDetail>> pageSupport = new PageSupport<>();

        OrderMainExample orderMainExample = new OrderMainExample();
        OrderMainExample.Criteria criteria = orderMainExample.createCriteria();
        criteria.andUserIdEqualTo(userId);

        if (pageSize <= 0) {
            pageSupport.setPageSize(SystemConstant.SYS_INIT_PAGE_SIZE);
        } else {
            pageSupport.setPageSize(pageSize);
        }

        if (currPageNo <= 0) {
            pageSupport.setCurrPageNo(SystemConstant.SYS_INIT_PAGE_NO);
        } else {
            pageSupport.setCurrPageNo(currPageNo);
        }

        // 当orderStatus为空时默认查询所有订单信息，不为空时依据orderStatus查询订单信息
        if (orderStatus != null && orderStatus != 0) {
            criteria.andOrderStatusEqualTo(orderStatus);
        }

        orderMainExample.setOrderByClause("order_time desc");

        pageSupport.setTotalCount((int) orderMainMapper.countByExample(orderMainExample));

        orderMainExample.setOffset((long) pageSupport.getPageIndex());
        orderMainExample.setLimit(pageSupport.getPageSize());

        // 判断用户是否有历史订单
        List<OrderMain> orderMainList = orderMainMapper.selectByExample(orderMainExample);
        if(orderMainList == null || orderMainList.size() == 0){
            // 该用户没有订单
            pageSupport.setData(null);
        }

        // 用户拥有历史订单，进行返回数据处理
        List<OrderMain<OrderDetail>> orderMainNewList = new ArrayList<>();
        for(int i = 0;i < orderMainList.size();i++){
            OrderMain orderMain = new OrderMain();
            orderMain.setOrderNum(orderMainList.get(i).getOrderNum());

            // 获取订单中商品的具体信息
            Map<String, CartProductReturn> cartProductReturnMap = new HashMap<>();
            OrderDetailExample orderDetailExample = new OrderDetailExample();
            orderDetailExample.createCriteria().andOrderNumEqualTo(orderMainList.get(i).getOrderNum());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectByExample(orderDetailExample);
            for(int j = 0;j < orderDetailList.size();j++){
                CartProductReturn cartProductReturn = new CartProductReturn();
                cartProductReturn.setProductName(this.getProductById(orderDetailList.get(j).getProductId()).getProductName());
                cartProductReturn.setProductDescription(this.getProductById(orderDetailList.get(j).getProductId()).getProductDescription());
                cartProductReturn.setPrice(this.getProductById(orderDetailList.get(j).getProductId()).getPrice());
                cartProductReturn.setQuantity(orderDetailList.get(j).getProductQuantity());
                cartProductReturnMap.put(this.getProductById(orderDetailList.get(j).getProductId()).getProductCode(), cartProductReturn);
            }
            orderMain.setOrderDetail(cartProductReturnMap);

            orderMain.setReceiverName(orderMainList.get(i).getReceiverName());
            orderMain.setReceiverPhone(orderMainList.get(i).getReceiverPhone());
            orderMain.setReceiverProvince(orderMainList.get(i).getReceiverProvince());
            orderMain.setReceiverCity(orderMainList.get(i).getReceiverCity());
            orderMain.setReceiverDistrict(orderMainList.get(i).getReceiverDistrict());
            orderMain.setReceiverAddress(orderMainList.get(i).getReceiverAddress());
            orderMain.setPayType(orderMainList.get(i).getPayType());
            orderMain.setOrderAmount(orderMainList.get(i).getOrderAmount());
            orderMain.setCouponsAmount(orderMainList.get(i).getCouponsAmount());
            orderMain.setVipAmount(orderMainList.get(i).getVipAmount());
            orderMain.setFreight(orderMainList.get(i).getFreight());
            orderMain.setPayAmount(orderMainList.get(i).getPayAmount());
            orderMain.setOrderTime(orderMainList.get(i).getOrderTime());
            orderMain.setPayTime(orderMainList.get(i).getPayTime());
            orderMain.setOrderIntegral(orderMainList.get(i).getOrderIntegral());
            orderMain.setOrderStatus(orderMainList.get(i).getOrderStatus());
            orderMainNewList.add(orderMain);
        }
        pageSupport.setData(orderMainNewList);

        return pageSupport;
    }

    @Override
    public OrderMain getStatusByOrderNum(String orderNum) {
        OrderMainExample orderMainExample = new OrderMainExample();

        orderMainExample.createCriteria().andOrderNumEqualTo(orderNum);

        OrderMain orderMain = orderMainMapper.selectByExample(orderMainExample).get(0);

        return orderMain;
    }

    @Override
    public LogisticsInfo getLogisticsInfo(Integer logisticsId) {
        return logisticsInfoMapper.selectByPrimaryKey(logisticsId);
    }

    @Override
    public Stock getStockById(Integer productId) {
        StockExample stockExample = new StockExample();
        stockExample.createCriteria().andProductIdEqualTo(productId);
        return stockMapper.selectByExample(stockExample).get(0);
    }

    @Override
    public boolean putArrivalReminder(Integer userId, Integer productId, String userPhone) {
        ArrivalReminder arrivalReminder = new ArrivalReminder();
        arrivalReminder.setUserId(userId);
        arrivalReminder.setProductId(productId);
        arrivalReminder.setUserPhone(userPhone);
        return arrivalReminderMapper.insert(arrivalReminder) > 0;
    }

    @Override
    public List<ArrivalReminder> getAllArrivalReminder() {
        ArrivalReminderExample arrivalReminderExample = new ArrivalReminderExample();
        List<ArrivalReminder> arrivalReminderList = arrivalReminderMapper.selectByExample(arrivalReminderExample);
        if(arrivalReminderList == null || arrivalReminderList.size() == 0){
            return null;
        }
        return arrivalReminderMapper.selectByExample(arrivalReminderExample);
    }

    @Override
    public boolean delArrivalReminder(Integer reminderId) {
        return arrivalReminderMapper.deleteByPrimaryKey(reminderId) > 0;
    }

    @Override
    public List<Stock> getAllStock() {
        StockExample stockExample = new StockExample();
        stockExample.createCriteria().andCountEqualTo(0);
        List<Stock> stockList = stockMapper.selectByExample(stockExample);
        if(stockList == null || stockList.size() == 0){
            return null;
        }
        return stockList;
    }

    @Override
    public boolean updStock(Integer productId, Integer count) {
        StockExample stockExample = new StockExample();
        stockExample.createCriteria().andProductIdEqualTo(productId);
        List<Stock> stockList = stockMapper.selectByExample(stockExample);
        if(stockList == null || stockList.size() == 0){
            return false;
        }
        for(int i = 0;i < stockList.size();i++){
            Stock stock = stockList.get(i);
            stock.setCount(stock.getCount() + count);
            stockMapper.updateByPrimaryKey(stock);
        }
        return true;
    }

    @Override
    public boolean delCoupons(Integer couponsId) {
        return userCouponsMapper.deleteByPrimaryKey(couponsId) > 0;
    }

    @Override
    public List<UserCoupons> getCoupons(Integer userId, String couponsNum) {
        UserCouponsExample userCouponsExample = new UserCouponsExample();
        userCouponsExample.createCriteria().andUserIdEqualTo(userId).andCouponsNumEqualTo(couponsNum).andEndTimeGreaterThan(new Date());
        List<UserCoupons> userCouponsList = userCouponsMapper.selectByExample(userCouponsExample);
        if(userCouponsList == null || userCouponsList.size() == 0){
            return null;
        }
        return userCouponsList;
    }

    @Override
    public boolean delCartProduct(Integer userId) {
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andCheckedEqualTo(1);
        return cartMapper.deleteByExample(cartExample) > 0;
    }
}
